package com.lxf.cloudotherserve.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.lxf.cloudfeign.client.userClient.UserClient;
import com.lxf.cloudotherserve.bean.CommentIsLikeBean;
import com.lxf.cloudotherserve.bean.UserCommentBean;
import com.lxf.cloudotherserve.mapper.CommentIsLikeItemRepository;
import com.lxf.cloudotherserve.mapper.CommentIsLikeMapper;
import com.lxf.cloudotherserve.mapper.UserCommentItemRepository;
import com.lxf.cloudotherserve.service.BaseStrategy;
import com.lxf.cloudotherserve.service.CommentIsLikeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author 罗兴发
 * @data 2025/6/30 14:18
 * @description：评论点赞/踩踏-业务实现层
 */
@Slf4j
@Service
public class CommentIsLikeServiceImpl implements CommentIsLikeService {
    @Resource
    CommentIsLikeMapper commentIsLikeMapper;
    @Resource
    private CommentIsLikeItemRepository commentIsLikeItemRepository;

    @Resource
    private UserCommentItemRepository userCommentItemRepository;
    @Resource
    private Map<String, BaseStrategy> baseStrategyMap;

    @Resource
    private UserClient userClient;

    @Override
    @Transactional(rollbackFor = Exception.class)
    public String addCommentIsLike(JSONObject json, HttpServletRequest request) {
        JSONObject js = new JSONObject();
        //获取请求凭证,凭证中存放用户ID和用户名，存放格式为：userId_userName
        String secretToken = request.getHeader("secretToken");

        JSONObject j1 = new JSONObject();
        j1.put("redis_key",secretToken);
        //获取redis中缓存的token
        String o = userClient.getRedisData(j1);
        if (null!=o) {
            //截取请求头中存储的用户ID
            int secretTokenIndex = secretToken.lastIndexOf(":");
            String userIdSub = secretToken.substring(secretTokenIndex + 1);
            Integer userId = Integer.valueOf(userIdSub);//用户ID
            try {
                //前端参数
                Integer likeType = json.getInteger("like_type");//类型:0点赞 1踩
                Integer commentId = json.getInteger("comment_id");//评论ID
                // 根据用户ID和评论类型等获取用户是否已点赞获取踩踏
                Optional<CommentIsLikeBean> likes = commentIsLikeItemRepository.findAllByUserIdAndComId(userId, commentId);

                //需要更新点赞量或者踩踏量,所以查询评论的详情
                UserCommentBean userComment = userCommentItemRepository.findById(String.valueOf(commentId)).get();
                Integer likeNum = userComment.getLikeNum();
                Integer unLikeNum = userComment.getUnLikeNum();
                //时间规格化
                SimpleDateFormat sf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                String addTime = sf.format(new Date());

                //list封装
                List<CommentIsLikeBean> list = new ArrayList<>();

                //表示该用户已点赞或者已踩踏，需要删除相应记录
                if (likes.isPresent()){
                    CommentIsLikeBean commentIsLike = likes.get();
                    Integer type = commentIsLike.getCilType();
                    Integer cilId = commentIsLike.getCilId();
                    //删除es中记录
                    commentIsLikeItemRepository.deleteById(String.valueOf(cilId));

                    //删除mysql中记录
                    commentIsLikeMapper.deleteById(cilId);

                    // 用户相对操作：原本是选择点赞的，现在又选择踩踏，所以需要重新添加
                    if (type!=likeType) {

                        // 评论点赞踩踏对象实例化
                        CommentIsLikeBean com = new CommentIsLikeBean();
                        com.setComId(commentId);
                        com.setUserId(userId);
                        com.setCilType(likeType);
                        com.setAddTime(addTime);

                        list.add(com);
                    }
                    //把原有的数据量”作减一“操作
                    if (type==0){
                        //取消点赞，需要将点赞量减一
                        likeNum = likeNum -1;

                        //重新设置点赞量
                        userComment.setLikeNum(likeNum);
                    }
                    if (type==1){
                        //取消踩踏，需要将踩踏值减一
                        unLikeNum = unLikeNum - 1;
                        //重新设置点赞量
                        userComment.setUnLikeNum(unLikeNum);
                    }
                }else {// 用户点赞或踩踏操作

                    // 评论点赞踩踏对象实例化
                    CommentIsLikeBean com = new CommentIsLikeBean();
                    com.setComId(commentId);
                    com.setUserId(userId);
                    com.setCilType(likeType);
                    com.setAddTime(addTime);

                    list.add(com);
                }

                if (list.size()>0){
                    //添加点赞/踩踏记录
                    int flag = commentIsLikeMapper.addCommentIsLike(list);
                    if (flag<0){
                        js.put("code",401);
                        js.put("msg","Fails");
                    }else {
                        js.put("code",200);
                        js.put("msg","Success");

                        // 仅有点赞才发送消息通知
                        if (likeType==0){

                            //更新评论点赞量
                            likeNum = likeNum +1;
                            userComment.setLikeNum(likeNum);

                            // 根据用户ID查询用户信息
                            JSONObject js1 = new JSONObject();
                            js1.put("user_id",userId);

                            //根据用户ID查询评论者信息
                            String u = userClient.findById(js1);
                            JSONObject j2 = JSONObject.parseObject(u);
                            String data = j2.getString("data");

                            //实体数据返回
                            JSONObject j3 = JSONObject.parseObject(data);

                            String userName = j3.getString("userName");
                            String userHead = j3.getString("userHead");

                            String objId = userComment.getObjId();
                            Integer objType = userComment.getObjType();

                            // 根据类型获取相应信息
                            JSONObject jsonObject = new JSONObject();
                            jsonObject.put("obj_type",objType);

                            String d = userClient.getDataNameAndDesc(jsonObject);
                            JSONObject j4 = JSONObject.parseObject(d);

                            String name = j4.getString("name");

                            // 根据类型，获取相应信息
                            BaseStrategy baseStrategy = baseStrategyMap.get(name);
                            Map infos = baseStrategy.getInfos(objId,null);
                            String objTitle = String.valueOf(infos.get("objTitle"));
                            String proUserId = String.valueOf(infos.get("userId"));
                            String cover = String.valueOf(infos.get("cover"));

                            // 详细信息
                            String contentInfo = "<div><p id='objId'>"+objId+"</p><p id='objType'>"+objType+"</p><p id='objTitle'>"+objTitle+"</p><p id='cover'><img src='"+cover+"'></p></div>";
                            String usersInfo = "<div><p id='userId'>"+userId+"</p><p id='userName'>"+userName+"</p><p id='userHead'>"+userHead+"</p></div>";
                            String commentInfo = "<div>赞了你的评论<p id='commentId'>"+commentId+"</p></div>";

                            // 最终发送消息
                            String msg = contentInfo+usersInfo+commentInfo;

                            // 给评论发布者发送消息通知
                            JSONObject j = new JSONObject();
                            j.put("user_id",proUserId);
                            j.put("msg",msg);
                            j.put("msg_type",2);
                            j.put("f_user_id",0);
                            userClient.sendPrivateMsg(j);
                        }
                        if (likeType==1){
                            //更新评论踩踏量
                            unLikeNum = unLikeNum +1;
                            userComment.setUnLikeNum(unLikeNum);
                        }
                    }
                }
                //更新
                userCommentItemRepository.save(userComment);
            }catch (Exception e){
                js.put("code",500);
                js.put("msg",e.getMessage());
            }
        }else {
            js.put("code",400);
            js.put("msg","The Current Request is Invalid");
        }

        return JSONObject.toJSONString(js, SerializerFeature.WriteMapNullValue);
    }
}
